package role_service

import (
	"gorm.io/gorm"
	rd "pear-admin-layui-go/app/sys/role/domain"
	urd "pear-admin-layui-go/app/sys/user_role/domain"
	fd "pear-admin-layui-go/framework/database"
)

func UserRoles(id int64) []urd.RoleUserCheckboxResponse {
	var roleUsers []urd.RoleUserCheckboxResponse
	//fd.Db.Select("id", "name").Where("enable = true AND del_flag = false").Find(&roles)
	fd.Db.Model(&rd.Role{}).Select("sys_role.id as role_id, sys_role.name as role_name, sys_user_role.user_id as user_id").Joins("left join sys_user_role on sys_user_role.role_id = sys_role.id AND sys_user_role.user_id = ?", id).Scan(&roleUsers)
	return roleUsers
}

func EditPage(id int64) rd.Role {
	r := rd.Role{Id: id}
	fd.Db.Select("id", "name", "code", "remark").First(&r)
	return r
}

func Enable(rer *rd.RoleEnableRequest) *gorm.DB {
	return fd.Db.Model(rd.Role{Id: rer.Id}).Select("enable", "update_time", "update_name",
		"update_by").Updates(rd.Role{Enable: rer.Enable, UpdateTime: rer.UpdateTime, UpdateBy: rer.UpdateBy, UpdateName: rer.UpdateName})
}

func Edit(rer *rd.RoleEditRequest) (tx *gorm.DB) {
	return fd.Db.Model(rd.Role{Id: rer.Id}).Updates(rd.Role{Name: rer.Name, Code: rer.Code, Remark: rer.Remark, UpdateName: rer.UpdateName,
		UpdateBy: rer.UpdateBy, UpdateTime: rer.UpdateTime})
}

func Table(rtr *rd.RoleTableRequest) ([]rd.Role, int64) {
	var count int64
	db := fd.Db.Model(rd.Role{}).Where("del_flag = false")
	if rtr.Name != "" {
		db.Where("name like ?", "%"+rtr.Name+"%")
	}
	db.Count(&count)
	var roles []rd.Role
	db.Select("id", "name", "code", "enable", "remark", "create_time", "create_name", "update_time",
		"update_name").Limit(rtr.Limit).Offset((rtr.Page - 1) * rtr.Limit).Find(&roles)
	return roles, count
}

func Save(rsr *rd.RoleSaveRequest) (rd.Role, error) {
	r := rd.Role{
		Name:       rsr.Name,
		Code:       rsr.Code,
		Enable:     rsr.Enable,
		Remark:     rsr.Remark,
		CreateTime: rsr.CreateTime,
		CreateName: rsr.CreateName,
		CreateBy:   rsr.CreateBy,
		DelFlag:    false,
	}
	result := fd.Db.Create(&r)
	return r, result.Error
}
